package com.wgz.flag.service.impl;

import com.wgz.flag.domain.vo.GroupMemberVO;
import com.wgz.flag.entity.GroupMember;
import com.wgz.flag.exception.BaseException;
import com.wgz.flag.mapper.GroupMemberMapper;
import com.wgz.flag.service.GroupMemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class GroupMemberServiceImpl implements GroupMemberService {

    private final GroupMemberMapper groupMemberMapper;

    @Override
    public List<GroupMemberVO> getGroupMembers(Long groupId) {
        List<GroupMember> members = groupMemberMapper.selectByGroupId(groupId);
        return members.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public void kickMember(Long groupId, Long operatorId, Long targetId) {
        // 检查操作者权限
        GroupMember operator = checkOperatorPermission(groupId, operatorId);
        GroupMember target = checkTargetMember(groupId, targetId);

        // 检查是否有权限踢人
        if (operator.getRole() <= target.getRole() ){
            throw new BaseException("没有权限执行此操作");
        }

        // 用户自己退出群
        if (targetId.equals(operatorId)) {
            groupMemberMapper.updateStatus(groupId, targetId, 0);
            return;
        }

        groupMemberMapper.updateStatus(groupId, targetId, 0);
    }

    @Override
    public void muteMember(Long groupId, Long operatorId, Long targetId, Integer duration) {
        // 检查操作者权限
        GroupMember operator = checkOperatorPermission(groupId, operatorId);
        GroupMember target = checkTargetMember(groupId, targetId);

        if (operator.getRole() <= target.getRole()) {
            throw new BaseException("没有权限执行此操作");
        }

        LocalDateTime muteEndTime = LocalDateTime.now().plusMinutes(duration);
        groupMemberMapper.updateMuteTime(groupId, targetId, muteEndTime);
    }

    @Override
    public void unmuteMember(Long groupId, Long operatorId, Long targetId) {
        // 检查操作者权限
        GroupMember operator = checkOperatorPermission(groupId, operatorId);
        GroupMember target = groupMemberMapper.selectByGroupAndUserId(groupId, targetId);
        if(target == null || target.getStatus() != 2){
            throw new BaseException("目标不存在或目标已经被解除禁言");
        }
        if (operator.getRole() <= target.getRole()) {
            throw new BaseException("没有权限执行此操作");
        }

        groupMemberMapper.updateStatus(groupId, targetId, 1);
    }

    @Override
    public void setAdmin(Long groupId, Long operatorId, Long targetId) {
        // 检查操作者是否是群主
        GroupMember operator = checkOperatorPermission(groupId, operatorId);
        if (operator.getRole() != 2) {
            throw new BaseException("只有群主能设置管理员");
        }

        GroupMember target = checkTargetMember(groupId, targetId);
        groupMemberMapper.updateRole(groupId, targetId, 1);
    }

    @Override
    public List<Long> getGroupMemberIds(Long groupId) {
        return groupMemberMapper.selectMemberIdsByGroupId(groupId);
    }

    @Override
    public GroupMemberVO getGroupMember(Long groupId, Long userId) {
        GroupMember member = groupMemberMapper.selectByGroupAndUserId(groupId, userId);
        if (member == null || member.getStatus() != 1) {
            throw new BaseException("目标成员不存在");
        }
        return convertToVO(member);
    }

    private GroupMember checkOperatorPermission(Long groupId, Long operatorId) {
        GroupMember operator = groupMemberMapper.selectByGroupAndUserId(groupId, operatorId);
        if (operator == null || operator.getStatus() != 1) {
            throw new BaseException("无效的操作者");
        }
        if (operator.getRole() < 1) {
            throw new BaseException("没有权限执行此操作");
        }
        return operator;
    }

    /**
     * 检查目标成员是否在群内
     */
    private GroupMember checkTargetMember(Long groupId, Long targetId) {
        GroupMember target = groupMemberMapper.selectByGroupAndUserId(groupId, targetId);
        if (target == null || target.getStatus() != 1) {
            throw new BaseException("目标成员不存在");
        }
        return target;
    }

    private GroupMemberVO convertToVO(GroupMember member) {
        if (member == null) {
            return null;
        }
        GroupMemberVO vo = new GroupMemberVO();
        BeanUtils.copyProperties(member, vo);
        if (member.getUser() != null) {
            vo.setUsername(member.getUser().getUsername());
            vo.setAvatar(member.getUser().getAvatar());
        }
        return vo;
    }
}